/*
 * @Author: zhang zhijiang 2824735304@qq.com
 * @Date: 2025-03-21 15:49:51
 * @LastEditors: zhang zhijiang 2824735304@qq.com
 * @LastEditTime: 2025-03-21 17:17:52
 * @FilePath: /linux/test_3_21/mythread.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include<string>
#include<unistd.h>
#include<pthread.h>
#include<vector>
#include"lock.hpp"
using namespace std;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
class thread
{
    public:
    thread(const string& threadname,int number,pthread_mutex_t *lock)
    :_threadname(threadname),_number(number),_lock(lock)
    {}
    public:
    int _number;
    string _threadname;
    pthread_mutex_t * _lock;
};
int tickets = 1000;
void* rountine(void* argvs)
{
    thread* td= static_cast<thread*>(argvs);
    const char* name = td->_threadname.c_str();

    while(1)
    {   
    //pthread_mutex_lock(td->_lock);//加锁 只有拥有锁的才可以进入if
    mylock lclock(&lock);//
        if(tickets>0)
        {
            usleep(100);
            printf("%s is running...... ",name);
            printf("tickets:%d\n",tickets);
            tickets--;
          //  pthread_mutex_unlock(td->_lock);
        }
        else
        {
   // pthread_mutex_unlock(td->_lock);
    break;
        }
        usleep(13);//执行其他的

    }
    printf("%s quit",name);
    return nullptr;
}
int main()
{
    pthread_mutex_t lock;
    // pthread_mutex_init(&lock,nullptr);
    vector<pthread_t> tids;
    vector<thread*> threads;  
    for(int i = 0;i<4;i++)
    {
        pthread_t tid;
        string name = "thread-" + to_string(i);
        thread *td = new thread(name,i,&lock);
        threads.push_back(td);
        pthread_create(&tid,nullptr,rountine,threads[i]);
        tids.push_back(tid);
    }
    for(auto e:tids )
    {
        pthread_join(e,nullptr);
    }

    for(auto e:threads)
    {
        delete e;
    }
    // pthread_mutex_destroy(&lock);
    return 0;
}